package gitobject;

import sha1.SHA1;
import zlib.ZLibUtils;

import java.io.*;

public class Blob extends GitObject{
    
	public String getFmt(){
        return fmt;
    }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }
    public String getKey() { return key; }
    public Blob(){};
    /**
     * Constructing blob object from a file
     * @param file
     * @throws Exception
     */
    public Blob(File file) throws Exception {
        fmt = "blob";
        mode = "100644";
        value = getValue(file);
        key = genKey(file);
        path = getPath();
//        writeObject();
//        compressWrite();
//        System.out.println("creating a blob");
    }

    /**
     * Deserialize a blob object from an existed hash file in .jit/objects.
     * @param Id
     * @return Blob
     * @throws IOException
     */
    public static Blob deserialize(String Id) throws IOException {
        Blob blob = new Blob();
        try{
        /**
         * Add your code here. -- DONE
         */
         // for writeObject() method
//            String curPath = "worktree"+ File.separator +".jit"+ File.separator +"objects" +
//                    File.separator + Id.substring(0, 2) + File.separator + Id.substring(2);
//            File f = new File(curPath);
            // 反序列化
//            ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
//            blob = (Blob) in.readObject();
         // for compressWrite() method
            String curPath = "worktree"+ File.separator +".jit"+ File.separator +"objects" +
                    File.separator + Id.substring(0, 2) + File.separator + Id.substring(2);
            File f = new File(curPath);
            FileInputStream fis = new FileInputStream(f);
            // 解压缩文件输入流
            byte[] compressedData = ZLibUtils.decompress(fis);
            // 执行解压缩
            byte[] data = ZLibUtils.decompress(compressedData);
            // 反序列化
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
            blob = (Blob) in.readObject();
            in.close();
         }catch (Exception e){
            e.printStackTrace();
        }
//        System.out.println(blob.value);
        return blob;
    }

    /**
     * Generate key from file.
     * @param file
     * @return String
     * @throws Exception
     */
    public String genKey(File file) throws Exception {
        String key = SHA1.getHash(file);
        return key;
    }
    @Override
    public String toString(){
        return "100644 blob " + key;
    }

}
